<template>
  <el-container style="background: #E4E7ED;height: 100vh">
    <el-header>
      <el-page-header @back="goBack" content="聊天页面" style="color: #FFFFFF">
      </el-page-header>
    </el-header>
    <el-main>
      <div class="">
        <div class="flex_row">
          <div>
            <JwChat-index ref="jwChat" v-model="socketMsg.msg" :taleList="taleList" :scrollType="scrollType"
              :toolConfig="tool" :placeholder="placeholder" :config="config" :showRightBox="showRightBox"
              @enter="bindEnter" @clickTalk="talkEvent" width="800px" height="600px">
            </JwChat-index>
          </div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>

export default {
  name: "wechat",
  data() {
    return {
      scrollType: 'noroll', // scroll  noroll 俩种类型
      placeholder: "发送图片 img|https://www.baidu.com/img/flexible/logo/pc/result.png 发送视频 video|https://www.w3school.com.cn/i/movie.mp4 ",
      taleList: [],
      tool: {
        callback: this.toolEvent
      },
      config: {
        img: "https://www.baidu.com/img/flexible/logo/pc/result.png",
        name: "JwChat",
        dept: "最简单、最便捷",
        callback: (e) => { console.log(e) },
        maxlength: 300,
      },
      showRightBox: false,
      //聊天
      url: "ws://212.64.21.176:9001/socket/chat/people ",
      message: "",
      text_content: "",
      userSocketInfo: [{
        nick_name: "",
        type: "",
        body: "",
      }],
      ws: null,
      socketMsg: {
        msg: "",
        from: "",
        to: "",
        group: false,
        all: false,
        group_id: "",
        user_id: "",
      },
      fromUser: {
        CreatedAt: "",
        DeletedAt: "",
        ID: "",
        UpdatedAt: "",
        friends: "",
        groups: "",
        img_id: "",
        img_http: "",
        name: "",
        nick_name: "",
        password: "",
        phone: "",
        sex: "",
        text: "",
        user_id: "",
        username: "",
      },
      toUser: {
        CreatedAt: "",
        DeletedAt: "",
        ID: "",
        UpdatedAt: "",
        friends: "",
        groups: "",
        img_id: "",
        img_http: "",
        name: "",
        nick_name: "",
        password: "",
        phone: "",
        sex: "",
        text: "",
        user_id: "",
        username: "",
      }
    }
  },
  methods: {
    /**
     * @description: 点击加载更多的回调函数
     * @param {*}
     * @return {*}
     */
    bindEnter(e) {
      let that = this
      let msg = this.socketMsg.msg
      if (!msg) return;
      let value = this.checkMediaType(msg)
      let list = msg.split("|")
      if (value === "image") {
        msg = "<img data-src='" + list[1] + "'/>"
      }
      if (value === "video") {
        msg = "<video data-src='" + list[1] + "' controls='controls'/>"
      }
      if (this.ws) {
        this.ws.send(JSON.stringify(this.socketMsg));
      }
      const msgObj = {
        "date": that.getCurrentDate(),
        "text": { "text": msg },
        "mine": true,
        "name": that.fromUser.nick_name,
        "img": that.fromUser.img_http,
      }
      that.taleList.push(msgObj)
    },
    //对消息进行校验拼接
    checkMediaType(url) {
      let list = url.split("|")
      if (list[0] === "img") {
        return "image"
      }
      if (list[0] === "video") {
        return "video"
      }
    },
    toolEvent(type, obj) {
      console.log('tools', type, obj)
    },
    talkEvent(play) {
      console.log(play)
    },
    //获得当前时间
    getCurrentDate() {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      let hour = now.getHours()
      let minutes = now.getMinutes();
      return year + "-" + month + "-" + day + " " + hour + ":" + minutes;
    },
    //聊天
    initWebsocket() {
      let that = this
      this.ws = new WebSocket(this.url);
      const self = this;
      this.ws.onopen = function (event) {
        // self.text_content = self.text_content + "已经打开连接!" + "\n";
        //初始化链接
        that.initConnect()
      };
      this.ws.onmessage = function (event) {
        let sign = event.data.split(":")
        if (sign.length !== 0 && sign[0] === "socket") {
          //登录成功;1;  -- 发送失败 0
          let msgType = sign[1].split(";")
          if (msgType[2] === "0") {
            that.$message.error(msgType[0])
            that.userSocketInfo.pop()
          } else {
            // that.$message({
            //   message: msgType[0],
            //   type: "success",
            // });
            return
          }
        } else {
          let format = { mine: false, name: "", img: "" }
          let demo = { msg: "", from: "", to: "", group: "", all: "", group_id: "" }
          demo = JSON.parse(event.data)
          // console.log(demo)
          let value = that.checkMediaType(demo.msg)
          let list = demo.msg.split("|")
          if (value === "image") {
            demo.msg = "<img data-src='" + list[1] + "'/>"
          }
          if (value === "video") {
            demo.msg = "<video data-src='" + list[1] + "' controls='controls'/>"
          }
          if (demo.from === that.fromUser.user_id) {
            format.mine = true
            format.name = that.fromUser.nick_name
            format.img = that.fromUser.img_http
          } else {
            format.mine = false
            format.name = that.toUser.nick_name
            format.img = that.toUser.img_http
          }
          const msgObj = {
            "date": that.getCurrentDate(),
            "text": { "text": demo.msg },
            "mine": format.mine,
            "name": format.name,
            "img": format.img,
          }
          that.taleList.push(msgObj)
        }
      };
      this.ws.onclose = function (event) {
        // self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
    },
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    send() {
      let that = this
      let send = { nick_name: that.socketMsg.from, type: "right", body: that.socketMsg.msg }
      that.userSocketInfo.push(send)
      if (this.ws) {
        // console.log(this.socketMsg)
        this.ws.send(JSON.stringify(this.socketMsg));
        that.userSocketInfo.push(send)
      } else {
        // alert("未连接到服务器");
      }
    },
    //获得router内容
    getParam() {
      this.socketMsg.from = this.$route.params.form
      this.socketMsg.to = this.$route.params.to
      this.socketMsg.user_id = this.socketMsg.from
    },
    //查看个人信息
    getUserInfoF() {
      let token = localStorage.getItem("token")
      let that = this
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": "Bearer " + token
        },
        method: 'get',
        url: '/user/info/user_id?user_id=' + this.socketMsg.from,
      }).then((res) => {
        let result = res.data
        if (result.code === 1000) {
          that.fromUser = result.data
        }
      })
    },
    getUserInfoT() {
      let token = localStorage.getItem("token")
      let that = this
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": "Bearer " + token
        },
        method: 'get',
        url: '/user/info/user_id?user_id=' + this.socketMsg.to,
      }).then((res) => {
        let result = res.data
        if (result.code === 1000) {
          that.toUser = result.data
          this.config.img = this.toUser.img_http
          this.config.name = this.toUser.nick_name
          this.config.dept = this.toUser.text
        }
      })
    },
    initConnect() {
      let that = this
      //初始化链接发空消息
      let send = { nick_name: that.socketMsg.from, type: "right", body: "" }
      if (this.ws) {
        this.ws.send(JSON.stringify(this.socketMsg));
        that.$message.success("初始化成功")
      }
    },
    goBack() {
      this.$router.push("/index")
    }
  },
  beforeDestroy() {
    if (this.vantaEffect) {
      this.vantaEffect.destroy()
    }
  },
  mounted() {
  },
  created() {
    this.getParam()
    //获得用户信息
    this.getUserInfoF()
    this.getUserInfoT()
    this.initWebsocket()
  },
  destroyed() {
    this.exit()
  },
}
</script>
<style scoped lang="less">
.out {}

.flex_column {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.flex_row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

/**/
.right {
  text-align: right;
}

.left {
  text-align: left;
}

.box-card {
  width: 80%;
}

.flex_column {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.flex_row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.el-header {
  background-image: -webkit-linear-gradient(right, #fff1eb 0%, #ace0f9 100%);
  /*background-image: -webkit-linear-gradient(right, #a1c4fd 0%, #c2e9fb 100%);*/
}

.el-main {
  color: #333;
  text-align: center;
  /*background-image: -webkit-linear-gradient(right, #a1c4fd 0%, #c2e9fb 100%);*/
  background-image: -webkit-linear-gradient(right, #fff1eb 0%, #ace0f9 100%);
}
</style>